import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import { Vector as VectorSource, XYZ } from 'ol/source';
import { fromLonLat } from "ol/proj";
import { DragPan, DragZoom, KeyboardPan, KeyboardZoom, MouseWheelZoom, PinchZoom } from "ol/interaction";
import { ScaleLine, Zoom } from "ol/control";
import { Vector as VectorLayer } from "ol/layer";

export class MapBase {

	private mapObj!: Map;
	public getOlMap = () => this.mapObj;

	// 图层名字
	public readonly drawLayerName: string = 'vector-draw';

	constructor(
		private dom: HTMLDivElement,
	) {
		this.initMap();
	}

	/** 生成地图 */
	private initMap(): void {
		let mapLayers = [];
		// XYZ
		let tileLayer = new TileLayer({
			source: new XYZ({
				url: 'https://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
			}),
			zIndex: 0,
		});
		mapLayers.push(tileLayer);
		// 绘制层
		let vectorDrawLayer = new VectorLayer({
			source: new VectorSource(),
			zIndex: 10,
		});
		vectorDrawLayer.setProperties({ 'name': this.drawLayerName });
		mapLayers.push(vectorDrawLayer);
		/** 实例化地图 */
		this.mapObj = new Map({
			target: this.dom,
			layers: mapLayers,
			view: new View({
				projection: 'EPSG:3857',
				center: fromLonLat([105.203317, 37.506176]),
				zoom: 4,
				maxZoom: 21,
				minZoom: 0
			}),
			interactions: [
				new DragPan(),
				new PinchZoom(),
				new KeyboardPan(),
				new KeyboardZoom(),
				new MouseWheelZoom(),
				new DragZoom(),
			],
			controls: [
				new Zoom(),
				new ScaleLine(),
			]
		});
	}

	/** 根据name获取图层 */
	getVectorLayerByName(name: string): VectorLayer<any> | null {
		if (this.mapObj == null) {
			return null;
		}
		let layers = this.mapObj.getLayers().getArray();
		for (let i = 0; i < layers.length; i++) {
			if (name == layers[i].getProperties()['name']) {
				return <VectorLayer<any>>layers[i];
			}
		}
		return null;
	}

}
